package com.djk.service.impl;

import com.djk.constants.SessionKeys;
import com.djk.pojo.User;
import com.djk.service.UserService;
import com.djk.mapper.UserMapper;
import com.djk.utils.IdUtil;
import com.djk.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;

/**
 * @author 联想
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-02-19 22:45:43
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 1.参数校验
     * 2.根据用户名，是否有该用户
     * 3.比对密码是否相同
     * 4.隐藏掉密码
     * 5.存入session
     *
     * @param user
     * @param session
     * @return
     */
    @Override
    public Result login(User user, HttpSession session) {
        if (!StringUtils.hasLength(user.getUsername()) || !StringUtils.hasLength(user.getPassword())) {
            return Result.usernameOrPasswordError();
        }
        User loginUser = null;
        try {
            loginUser = userMapper.queryByUsername(user.getUsername());
            //查找用户
            if (loginUser == null) {
                return Result.usernameError();
            }
            //校验密码
            if (!encoder.matches(user.getPassword(), loginUser.getPassword())) {
                //检验失败
                return Result.passwordError();
            }
        } catch (Exception e) {
            log.error("检验用户时异常：{}", e);
            return Result.error();
        }
        loginUser.setPassword("");
        session.setAttribute(SessionKeys.USER_INFO_SESSION, loginUser);
        return Result.ok(loginUser);
    }
}




